# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 鸢尾花_KNN算法实现分类.py
# @Author: dongguangwen
# @Date  : 2025-01-19 18:14
# 0.导入工具包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 1.加载数据集
iris_data = load_iris()
# print(iris_data)
# print(iris_data.feature_names)

# 2.数据展示
iris_df = pd.DataFrame(iris_data['data'], columns=iris_data.feature_names)
iris_df['label'] = iris_data['target']
# print(iris_df.head(5))
# print(iris_data.feature_names)
# sns.lmplot(x='sepal length (cm)', y='sepal width (cm)', data=iris_df, hue='label')
# plt.show()

# 3.特征工程（预处理-标准化）
# 3.1 数据集划分
x_train, x_test, y_train, y_test = train_test_split(iris_data['data'], iris_data.target, test_size=0.3, random_state=22)
print(len(iris_data.data))  # 150
print(len(x_train))  # 105

# 3.2 标准化
process = StandardScaler()
x_train = process.fit_transform(x_train)
x_test = process.transform(x_test)

# 4.模型训练
# 4.1 实力化
model = KNeighborsClassifier(n_neighbors=3)

# 4.2 调用fit方法
model.fit(x_train, y_train)

# 5.模型预测
x = [[5.1, 3.5, 1.4, 0.2]]
x = process.transform(x)
y_pred = model.predict(x)
print(y_pred)  # [0]


# 6.模型评估（准确率）
# 6.1 使用预测结果
y_pred = model.predict(x_test)
acc = accuracy_score(y_test, y_pred)
print('Accuracy', acc)  # Accuracy 0.9555555555555556

# 6.2 直接计算
acc = model.score(x_test, y_test)
print('Accuracy', acc)  # Accuracy 0.9555555555555556

"""
150
105
[0]
Accuracy 0.9555555555555556
Accuracy 0.9555555555555556
"""